<?php
namespace WebApper\Shortcode;

/*
 * [service]
 *
 */
 class CalenderMonth extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'calenderMonth';    

    /**
     * Handles the add post shortcode
     *
     * @param array $atts
     */
	 
    public function shortcode( $atts ) {

			global $wpdb, $webapper, $current_user;
			$currentUserRole = strtolower($current_user->roles[0]);
			$serviceTable = $webapper->tables->services;
			$scheduleTable = $webapper->tables->schedules;
			$serviceResults = $wpdb->get_results("Select * from {$serviceTable} ", ARRAY_A);
		?>
        <div class="btn-group" style="width:10%; float:left; padding-bottom:10px;">
          <?php if($currentUserRole == "administrator"){ ?>
          <button type="button" class="btn btn-primary">Staff</button>
          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button>
          <ul class="dropdown-menu" role="menu" style="padding-left:5px;">
            <?php 
                        $blogusers = get_users('blog_id=1&orderby=nicename&role=Staff');
                        foreach ($blogusers as $user)
                        {
                            echo '<li>
                           <label class="checkbox" >
                            <input  type="checkbox" name="staffName[]" id="staffName_'.$user->ID.'" value="'.$user->ID.'" onclick="LoadStaffCalendar(this.id, this.value);" >'.$user->display_name.'</label></li>';
                        }		  
                      ?>
          </ul>
          <?php } ?>
        </div>
        <div style="width:50%; float:left; ">
          <div style="width:100px; float:left;">
            <label class="checkbox">
              <input name="" type="checkbox" value="ddd" />
              Bookings</label>
          </div>
          <div style="width:100px; float:left;">
            <label class="checkbox">
              <input name="" type="checkbox" value="ddd" />
              Events</label>
          </div>
          <div style="width:100px; float:left;">
            <label class="checkbox">
              <input name="" type="checkbox" value="ddd" />
              Tasks</label>
          </div>
        </div>
        <div class="btn-group" style="width:100%;">
          <input type="hidden" name="action" id="action" value="web_apper<?php echo $this->shortcode; ?>" />
          <input type="hidden" name="web_apper_nonce" id="web_apper_nonce" value="<?php echo wp_create_nonce( 'WebApperAwesomeness!87' ); ?>" />
          <button type="button" class="btn btn-primary">Services</button>
          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button>
          <ul class="dropdown-menu" role="menu">
            <?php 
                    $service_table = $webapper->tables->services;
                    $rows = $wpdb->get_results("SELECT * FROM  $service_table", ARRAY_A);
                    if(count($rows) >0)
                    {
                        $count=0;
                        foreach ($rows as $row) {
                            echo '<li><a href="javascript:void(0);" onclick="javascript:LoadCalendarService('.$row['service_id'].');">'.$row['service_name'].'</a></li>';
                            $count++;
                        }
                    }
                    else
                    {
                        echo '<li><a href="javascript:void(0);">No record found.</a></li>';
                    }
                  ?>
          </ul>
        </div>
        <div style="height:5px;"></div>
        <input name="hidstaffId" id="hidstaffId" type="hidden" value="" />
        <input name="hidServiceId" id="hidServiceId" type="hidden" value="" />
        <!-- Info Modal -->
        <div id="infoModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h3 id="infoModalLabel">Heads Up!</h3>
          </div>
          <div class="modal-body">
            <div id="deleteWarning" style="display: block;">
              <p><span class="label label-info">Info</span>&nbsp;Please select a Staff and Service first. To do so, simply click on the Staff and Service you would like to change.</p>
            </div>
          </div>
          <div class="modal-footer">
            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
          </div>
        </div>
<!-- End Info MODAL-->
		<!-- Display Calendar Control -->
		<div id='calendar'></div>
		<script type="text/javascript">
			jQuery(document).ready(function($) {		
				var date = new Date();
				var d = date.getDate();
				var m = date.getMonth();
				var y = date.getFullYear();		
				$('#calendar').fullCalendar({ //initialize the calendar Control
					theme: true,
					header: { //calendar header option
						left: 'prev,next today',
						center: 'title',
						right: 'month,agendaWeek,agendaDay',				
					},
					editable: false,
					<?php if ($currentUserRole == 'administrator') {  ?>	
					events: <?php  echo json_encode($this->get_administrator_view()); ?>,
					<?php } ?>	
					timeFormat: 'hh:mm tt' ,
					eventColor: '#3d8af7;',
					eventTextColor: '#ffffff'	  				
				});
			});
		
		var staffIdArray = Array(); //global array used for storing
		var LoadStaffId = function(staffId, staffValue)
		{
			if(document.getElementById(staffId).checked)
			{
				staffIdArray.push(staffValue); 
			}
			else
			{
				RemoveItem(staffIdArray, staffValue);
			}
			document.getElementById('hidstaffId').value= staffIdArray;
		}
	
		var LoadCalendarService = function(serviceId)
		{
			var action = document.getElementById('action').value;
			var web_apper_nonce = document.getElementById('web_apper_nonce').value;	
			jQuery.ajax({
				url: "<?php echo site_url('wp-admin/admin-ajax.php'); ?>",
				type: "post",
				dataType: "json",
				data: {action: action, web_apper_nonce: web_apper_nonce, serviceId : serviceId},
				success: function(response) {
					jQuery('#calendar').html(response);
					jQuery('#calendar').fullCalendar({
						theme: true,
						header: {
							left: 'prev,next today',
							center: 'title',
							right: 'month,agendaWeek,agendaDay',				
						},
						editable: false,							
						events: response,
						<?php if($currentUserRole =="operator" || $currentUserRole == 'administrator'){ ?>	
							eventColor: 'transparent',
							eventTextColor: '#1464f6'
						<?php } else if($currentUserRole =="staff"){ ?>
							timeFormat: 'hh:mm tt' ,
							eventColor: '#3d8af7;',
							eventTextColor: '#ffffff'
						<?php }  ?>				
					});
				}
			});
		}
		function RemoveItem(arr, item) {
		  for(var i = arr.length; i--;) {
			  if(arr[i] === item) {
				  arr.splice(i, 1);
			  }
		  }
		}
		var LoadStaffCalendar = function(staffId, staffValue) {
			LoadStaffId(staffId, staffValue);
			var action = document.getElementById('action').value;
			var web_apper_nonce = document.getElementById('web_apper_nonce').value;	
			var staffId = document.getElementById('hidstaffId').value;
			jQuery.ajax({
				url: "<?php echo site_url('wp-admin/admin-ajax.php'); ?>",
				type: "post",
				dataType: "json",
				data: {action: action, web_apper_nonce: web_apper_nonce, staffId: staffId},
				success: function(response) {
					jQuery('#calendar').html(response);
					jQuery('#calendar').fullCalendar({
						theme: true,
						header: {
							left: 'prev,next today',
							center: 'title',
							right: 'month,agendaWeek,agendaDay',				
						},
						editable: false,							
						events: response,
						timeFormat: 'hh:mm tt' ,
						eventColor: '#3d8af7;',
						eventTextColor: '#ffffff'
					});
				}
			});
		}
	</script>
<?php	
	}
	
	/**
	 * Handles ajax requests
	 *
	 * @since 1.0
	 */
	function sendAjaxResponse() {
		global $current_user;
		$currentUserRole = strtolower($current_user->roles[0]);	
		check_ajax_referer( 'WebApperAwesomeness!87', 'web_apper_nonce' );  // Verify the security nonce
		if ( $_POST['serviceId']) {
			if($currentUserRole =="operator" || $currentUserRole == 'administrator'){
				echo json_encode( $this->get_available_operator_time_slot());
			}
			else if($currentUserRole =="staff"){
				echo json_encode( $this->get_available_staff_time_slot());
			}
		}
		else {
			echo json_encode( $this->get_administrator_view());
		}
		die();  // Prevents ajax from returning a '0'
	}
	/**
	 * Get Available Service Time For Operator View
	 *
	 * @since 1.0
	 */
	 public function get_available_operator_time_slot()
	 { 
		global $webapper, $wpdb, $current_user;
		$serviceId 		= $_POST['serviceId'];
		$serviceTable 	= $webapper->tables->services;
		$scheduleTable 	= $webapper->tables->schedules;
		$bookingTable 	= $webapper->tables->booking;
		$serviceResults = $wpdb->get_results($wpdb->prepare("Select * from {$serviceTable} where service_id=%d",$serviceId), ARRAY_A);
		$count = 0;
		$curentDate = date('Y-m-d');
		$events = array();
		$x=0;
		$ranges =  create_date_range_array(date('Y-m-d', strtotime("-365 days")),  date('Y-m-d', strtotime("+365 days")));
		foreach($ranges as $range){
			$jd=cal_to_jd(CAL_GREGORIAN, date("m", strtotime($range)),date("d", strtotime($range)),date("Y", strtotime($range))); 
			$currentDayId = jddayofweek( $jd,3);
			foreach($serviceResults as $result){
				for($i=0; $i<7 ; $i++){
					if($currentDayId == $i){
						$scheduleResults = $wpdb->get_results("Select * from {$scheduleTable} where  service_id =".$result['service_id']." and week_num=".$i."", ARRAY_A);
						$minMaxResults = $wpdb->get_results("Select min(startTime) as min,max(endTime) as max from {$scheduleTable} where  service_id =".$result['service_id']." and week_num=".$i."", ARRAY_A);
						foreach($scheduleResults as $scheduleResult){
							$timeDiff = ((int)$scheduleResult['endTime']) - ((int)$scheduleResult['startTime']);
							$count =(int)$count + (int)((int)$timeDiff / (int)$result['service_duration']);						
						}	
						$events[$x]['id'] = $result['service_id'];
						if($count !=0){	
							$bookingCount = $wpdb->get_results($wpdb->prepare("Select ifnull(count(booking_id), 0) as totalCount from {$bookingTable} where  service_id =%d and week_num=%d and reserveDate=%s", $serviceId, $i, $range), ARRAY_A);
							$remainingOpen = ((int)$count - (int)$bookingCount[0]['totalCount']);		
							$events[$x]['title'] = ((int)$count - (int)$bookingCount[0]['totalCount'])." Open";
						}
						$events[$x]['start'] = $range;
						$events[$x]['end'] = $range;
						if($remainingOpen >0)
						{
							$events[$x]['url'] = get_option('siteurl')."/booking/?serviceId=".$serviceId."&wek_num=".$i."&date=".$range;
						}
						$events[$x]['allDay'] = true;						
						$x++;
						break;						
					}						
				}
				$count = 0;
			}			
		}	
		return 	$events;
	 }
	 
	 /**
	 * Get Available Service Time For Staff View
	 *
	 * @since 1.0
	 */
	 public function get_available_staff_time_slot()
	 {		 
		global $webapper, $wpdb, $current_user;
		$staffId 		= $current_user->ID;
		$serviceId 		= $_POST['serviceId'];
		$serviceTable 	= $webapper->tables->services;
		$scheduleTable 	= $webapper->tables->schedules;
		$bookingTable 	= $webapper->tables->booking;
		$serviceResult	= $wpdb->get_results($wpdb->prepare("Select * from {$serviceTable} where service_id=%d",$serviceId), ARRAY_A);
		$timeDuration 	= $serviceResult[0]['service_duration'];
		$count = 0;
		$curentDate = date('Y-m-d');
		$events = array();
		$x=0;
		$ranges =  create_date_range_array(date('Y-m-d', strtotime("-365 days")),  date('Y-m-d', strtotime("+365 days")));
		foreach($ranges as $range){
			$jd=cal_to_jd(CAL_GREGORIAN, date("m", strtotime($range)),date("d", strtotime($range)),date("Y", strtotime($range))); 
			$currentDayId = jddayofweek( $jd,3);
			for($i=0; $i<7 ; $i++){
				if($currentDayId == $i){
					$bookingTimeSlots = $wpdb->get_results($wpdb->prepare("select * from {$bookingTable} where service_id=%d and week_num=%d and reserveDate=%s and user_id=%d", $serviceId, $i, $range, $staffId), ARRAY_A);
					foreach($bookingTimeSlots as $bookingTimeSlot){
						$firstName = get_post_meta( $bookingTimeSlot['postID'], 'first-name' );
						$lastName  = get_post_meta( $bookingTimeSlot['postID'], 'last-name' );
						$totalName = $firstName[0]." ".$lastName[0];
						$timeStartSlot = date('H:i', strtotime($bookingTimeSlot['reserveTime']));
						$timeEndSlot = date('H:i', strtotime($bookingTimeSlot['reserveTime'] . ' + '.$timeDuration.' minutes')); 
						$events[$x]['id'] = $x;
						$events[$x]['title'] = $totalName;
						$events[$x]['start'] = $range." ".$timeStartSlot;
						$events[$x]['end'] = $range." ".$timeEndSlot;
						$events[$x]['allDay'] = false;						
						$x++;
					}
				}						
			}
			$count = 0;
		}	
		return 	$events;
	 
	 }
	 
	 /**
	 * Administrator View
	 *
	 * @since 1.0
	 */
	 public function get_administrator_view()
	 {
		global $webapper, $wpdb, $current_user;
		$staffId 		= $current_user->ID;
		if($_POST['staffId']) {
			$staffIds	= explode(",",$_POST['staffId']);
		}
		else {
			$staffIds  = get_staff_users();
		}		
		$serviceTable 	= $webapper->tables->services;
		$scheduleTable 	= $webapper->tables->schedules;
		$bookingTable 	= $webapper->tables->booking;
		$serviceResults	= $wpdb->get_results("Select * from {$serviceTable}");
		$count = 0;
		$curentDate = date('Y-m-d');
		$events = array();
		$x=0;
		$ranges =  create_date_range_array(date('Y-m-d', strtotime("-365 days")),  date('Y-m-d', strtotime("+365 days")));
		foreach($ranges as $range){
			$jd=cal_to_jd(CAL_GREGORIAN, date("m", strtotime($range)),date("d", strtotime($range)),date("Y", strtotime($range))); 
			$currentDayId = jddayofweek( $jd,3);
			for($i=0; $i<7 ; $i++){
				if($currentDayId == $i){
					foreach($staffIds as $staffId){
						foreach($serviceResults as 	$serviceResult) {											
							$bookingTimeSlots = $wpdb->get_results($wpdb->prepare("select * from {$bookingTable} where service_id=%d and week_num=%d and reserveDate=%s and user_id=%d", $serviceResult->service_id , $i, $range, $staffId));
							if(count($bookingTimeSlots) >0){
								foreach($bookingTimeSlots as $bookingTimeSlot) {
									$user_id = $staffId;
									$key = 'nickname';
									$single = true;
									$user_name = get_user_meta( $user_id, $key, $single );
									$timeStartSlot = date('H:i', strtotime($bookingTimeSlot->reserveTime));
									$timeEndSlot = date('H:i', strtotime($bookingTimeSlot->reserveTime . ' + '.$serviceResult->service_duration.' minutes'));
									$title = $user_name." --- ".$serviceResult->service_name ;
									$events[$x]['id']		= $x;
									$events[$x]['title']	= $title;
									$events[$x]['start']	= $range." ".$timeStartSlot;
									$events[$x]['end']		= $range." ".$timeEndSlot;
									$events[$x]['allDay']	= false;						
									$x++;
								}
							}
						}
					}
				}						
			}
			$count = 0;
		}	
		return 	$events;	 
	 }	 
}

$initialize = new CalenderMonth(); 
?>
